package fair.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import fair.constant.MessageConstant;
import fair.entity.PageResult;
import fair.entity.QueryPageBean;
import fair.entity.Result;
import fair.pojo.CheckGroup;
import fair.pojo.CheckItem;
import fair.service.CheckItemService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author fair_wu
 * @version v1.0
 * @date 2021-01-17 下午 22:10
 */
@RestController
@RequestMapping("/checkItem")
public class CheckItemController {

    @Reference
    private CheckItemService service;

    @PreAuthorize("hasAuthority('CHECKITEM_ADD')")
    @PutMapping("/add")
    public Result add(@RequestBody CheckItem item){
        try {
            service.add(item);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
    }

    @PreAuthorize("hasAuthority('CHECKITEM_QUERY')")
    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPage){
        return service.pageQuery(queryPage.getCurrentPage(), queryPage.getPageSize(), queryPage.getQueryString());
    }

    @PreAuthorize("hasAuthority('CHECKITEM_DELETE')")
    @DeleteMapping("/delete")
    public Result delete(Integer id) {
        try {
            service.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_CHECKITEM_SUCCESS);
    }

    @PreAuthorize("hasAuthority('CHECKITEM_QUERY')")
    @GetMapping("/findById")
    public Result findById(Integer id){
        try {
            CheckItem item = service.findById(id);
            return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, item);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL);
        }
    }

    @PreAuthorize("hasAuthority('CHECKITEM_EDIT')")
    @PutMapping("/edit")
    public Result edit(@RequestBody CheckItem item){
        try {
            service.edit(item);
            return new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_CHECKITEM_FAIL);
        }
    }

    @PreAuthorize("hasAuthority('CHECKITEM_QUERY')")
    @GetMapping("/findAll")
    public Result findAll(){
        try {
            List <CheckItem> items = service.findAll();
            return new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS, items);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_CHECKITEM_FAIL);
        }
    }
}
